package hashtable;

/**
 * 哈希表（散列）  数组+链表 数组+二叉树 每个数组元素存放的是链表/二叉树
 * &可以作为缓存层的数据结构
 *
 */
public class HashTableDemo {
    public static void main(String[] args) {

    }
}

class Emp {
    private int id;
    private String name;
    public Emp next;

    public Emp(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Emp getNext() {
        return next;
    }

    public void setNext(Emp next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

/**
 * 创建员工链表
 */
class EmpLinkedList {
    //头指针，直接指向第一个雇员
    private Emp head;

    //添加雇员到链表
    public void add(Emp emp) {
        //如果是添加第一个雇员
        if (head == null) {
            head = emp;
        }
        //定位到链表末尾
        Emp cur = head;
        while (true) {
            if (cur.next == null) {
                break;
            }
            cur = cur.next;
        }
        cur.next = emp;
    }

    //遍历
    public void list() {
        if (head == null) {
            System.out.println("当前链表为空");
            return;
        }
        Emp cur = head;
        while (cur != null) {
            System.out.println(cur);
            cur = cur.next;
        }
    }

    //
    public Emp findEmpById(int id) {
        //判断链表是否为空
        if (head == null) {
            System.out.println("链表为空");
            return null;
        }
        Emp curEmp = head;
        while (true) {
            if (curEmp.getId() == id) {
                break;
            }
            if (curEmp.next == null) {
                curEmp = null;
                break;
            }
            curEmp = curEmp.next;
        }
        return curEmp;
    }
}

/**
 * 哈希表
 */
class EmpHashTab {
    private int size;
    private EmpLinkedList[] empLinkedListArray;

    public EmpHashTab(int size) {
        this.size = size;
        this.empLinkedListArray = new EmpLinkedList[size];
        //初始化每个链表
        for (int i = 0; i < size; i++) {
            empLinkedListArray[i] = new EmpLinkedList();
        }
    }

    //添加雇员
    public void add(Emp emp) {
        //根据id得到位置即哪条链表
        int no = hashFun(emp.getId());
        empLinkedListArray[no].add(emp);
    }

    //散列函数 用于确定元素在哪个链表
    public int hashFun(int id) {
        return id % size;
    }

    public void list() {
        for (int i = 0; i < size; i++) {
            empLinkedListArray[i].list();;
        }
    }

    public Emp findEmpById(int id) {
        //散列函数确定去哪找
        int no = hashFun(id);
        return empLinkedListArray[no].findEmpById(id);
    }

}
